package com.haohan.cloud.scm.manage.api.ctrl;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.haohan.cloud.scm.api.common.entity.req.UploadPhotoReq;
import com.haohan.cloud.scm.api.common.entity.resp.UploadPhotoResp;
import com.haohan.cloud.scm.api.constant.ScmCommonConstant;
import com.haohan.cloud.scm.api.manage.dto.PhotoGroupDTO;
import com.haohan.cloud.scm.common.tools.util.RUtil;
import com.haohan.cloud.scm.manage.core.PhotoManageCoreService;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.log.annotation.SysLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author dy
 * @date 2019/9/12
 */
@RestController
@AllArgsConstructor
@RequestMapping("/api/manage/photo")
@Api(value = "ApiManagePhoto", tags = "PhotoManage图片管理")
public class PhotoManageApiCtrl {
    private final PhotoManageCoreService photoManageCoreService;

    /**
     * 查询图片组图片详情
     *
     * @param groupNum
     * @return
     */
    @GetMapping("/fetchGroup")
    public R<PhotoGroupDTO> fetchGroup(@RequestParam("groupNum") String groupNum) {
        if (StrUtil.isBlank(groupNum)) {
            return R.failed("缺少参数groupNum");
        }
        PhotoGroupDTO photoGroupDTO = photoManageCoreService.fetchByGroupNum(groupNum);
        if (null == photoGroupDTO) {
            return R.failed("找不到该图片组");
        }
        return R.ok(photoGroupDTO);
    }

    @SysLog("上传图片")
    @PostMapping("/uploadPhoto")
    @ApiOperation(value = "图片上传")
    public R<UploadPhotoResp> uploadPhoto(@Validated UploadPhotoReq req) {
        MultipartFile mf = req.getFile();
        // 文件限制
        String fileName = mf.getOriginalFilename();
        String suffix = "";
        if (StrUtil.isNotBlank(fileName) && fileName.contains(StrUtil.DOT)) {
            suffix = fileName.substring(fileName.lastIndexOf(StrUtil.DOT)).toUpperCase();
        }
        if (!StrUtil.equalsAny(suffix, ScmCommonConstant.PHOTO_SUFFIX)) {
            String msg = ArrayUtil.join(ScmCommonConstant.PHOTO_SUFFIX, StrUtil.SPACE);
            msg = "图片格式有误,支持类型:".concat(msg);
            return R.failed(msg);
        }
        // 图片限制大小 2MB
        if (mf.getSize() > ScmCommonConstant.LIMIT_FILE_SIZE) {
            return R.failed("图片最大支持2MB");
        }
        return RUtil.success(photoManageCoreService.uploadPhoto(req.getFile(), req.getType(), suffix));
    }
}
